package com.eric.nioclient;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.eric.nioclient.data.Msg;
import com.eric.nioclient.service.Logic;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements View.OnClickListener,Logic.ServiceListener{


    Button btnSend;
    EditText sendText ;

    Logic logic = Logic.me();

    RecyclerView recordList ;
    List<Msg> mDatas = new ArrayList<Msg>();
    ChatAdapter mAdapter ;
    LinearLayoutManager layoutManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initUI();
        logic.addListener(this);
        initData();
    }

    private void initUI(){
        recordList = (RecyclerView) findViewById(R.id.chat_record);
        btnSend = (Button) findViewById(R.id.btn_send);
        sendText = (EditText)findViewById(R.id.send_text);
        btnSend.setOnClickListener(this);

        recordList.setLayoutManager(layoutManager = new LinearLayoutManager(this));
        recordList.setAdapter(mAdapter = new ChatAdapter());

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void initData(){
        for (int i =0 ; i < 20 ; i++){
            mDatas.add(Msg.obtainChat("user"+i,"msg"+1));
        }
        mDatas.add(Msg.obtainNotice("有人下线"));
        mDatas.add(Msg.obtainChat("eric","eric"));
    }

    @Override
    public void onClick(View v) {
        String sendTxt = sendText.getText().toString().trim();
        if(TextUtils.isEmpty(sendTxt)||sendTxt.length()>50){
            Toast.makeText(this,"发送的内容不能为空。",Toast.LENGTH_LONG).show();
            return ;
        }

        if(sendTxt.length()>50){
            Toast.makeText(this,"发送的内容太多了，想累死我呀^_^",Toast.LENGTH_LONG).show();
            return ;
        }
        logic.sendMsg(sendTxt);
        sendText.setText("");

//        int lastItem = layoutManager.findLastVisibleItemPosition();
//        recordList.scrollToPosition(21);
//        recordList.smoothScrollToPosition(lastItem);
//        Log.w(TAG," >>>> lastItem: "+mDatas.size());
    }

    @Override
    public void started() {

    }

    @Override
    public void stoped(Object obj) {
        Toast.makeText(this,"服务器已经关闭，跳转到登陆界面 >> ",Toast.LENGTH_LONG).show();
        Intent intent = new Intent(this,LoginActivity.class);
        startActivity(intent);
    }

    @Override
    public void connectActive() {

    }

    @Override
    public void receivedMsg(String sendUser, String msg) {
        mDatas.add(Msg.obtainChat(sendUser,msg));
        mAdapter.notifyDataSetChanged();
        scrollToLastPosition();
    }

    @Override
    public void receivedNotice(String msg) {
        mDatas.add(Msg.obtainNotice(msg));
        mAdapter.notifyDataSetChanged();
        scrollToLastPosition();
    }

    @Override
    public void loginSuccess() {

    }

    @Override
    public void loginFail(String msg) {

    }

    private void scrollToLastPosition(){
        recordList.scrollToPosition(mDatas.size()-1);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode){
            case KeyEvent.KEYCODE_BACK:
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.MyViewHolder> {

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
        {
            MyViewHolder holder =null ;
            switch (viewType) {
                case -1:
                    holder = new MyViewHolder(LayoutInflater.from(
                            MainActivity.this).inflate(R.layout.item_chat_left, parent,
                            false));
                    break;
                case 0:
                    holder = new MyViewHolder(LayoutInflater.from(
                            MainActivity.this).inflate(R.layout.item_chat_notice, parent,
                            false));
                    break;
                case 1:
                    holder = new MyViewHolder(LayoutInflater.from(
                            MainActivity.this).inflate(R.layout.item_chat_right, parent,
                            false));
                    break;
            }
            return holder;
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position)
        {
            Msg msg = mDatas.get(position);
            holder.msg = msg;
            holder.initView();

            switch (msg.type) {
                case Msg.TYPE_CHAT:
                    holder.tv.setText(msg.content);
                    holder.logo.setImageResource(R.drawable.ic_launcher_round);
                    break;
                case Msg.TYPE_NOTICE:
                    holder.tv.setText(msg.content);
                    break;
            }


        }

        public int getItemCount(){
                return mDatas.size() ;
        }

        @Override
        public int getItemViewType(int position) {
            Msg msg = mDatas.get(position);
            switch (msg.type) {
                case Msg.TYPE_CHAT:
                    if(logic.isMe(msg.user)) {
                      return 1;
                    }else {
                      return -1;
                    }
                case Msg.TYPE_NOTICE:
                    return 0;
            }
            return 0;
        }

        class MyViewHolder extends RecyclerView.ViewHolder {

            View root;
            TextView tv;
            ImageView logo;
            Msg msg ;

            public MyViewHolder(View view)
            {
                super(view);
                root = view;

            }
            public void initView(){
                tv = (TextView) root.findViewById(R.id.content);

                if(msg.type == Msg.TYPE_CHAT){
                    logo = (ImageView) root.findViewById(R.id.user_logo);
                    logo.setImageResource(getLogoIcon(msg.user));
                }

            }
        }
    }

    private int [] resid = {
            R.drawable.ic_launcher_round,
            R.drawable.ic_launcher_round,
            R.drawable.ic_launcher_round,
            R.drawable.ic_launcher_round,
            R.drawable.ic_launcher_round,
            R.drawable.ic_launcher_round,
            R.drawable.ic_launcher_round,
            R.drawable.ic_launcher_round,
            R.drawable.ic_launcher_round,
            R.drawable.ic_launcher_round

    };
    private int getLogoIcon(String name){
        if(TextUtils.isEmpty(name))return resid[0];
        Log.w(TAG,name+" >> ");
        return resid[Math.abs(name.hashCode()%10)];
    }

}

